package mybatis.testDemo.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import mybatis.testDemo.MybatisBean;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.sql.SQLException;

@Configuration
public class PgDataSource {

    public static void setupSqlSessionFactoryForPG(AnnotationConfigApplicationContext applicationContext) throws SQLException {

        GenericBeanDefinition definition = new GenericBeanDefinition();
        definition.setBeanClass(SqlSessionFactoryBean.class);
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);

        definition.getPropertyValues().add("configuration", configuration);
        definition.getPropertyValues().add("dataSource", pgDruidDataSource());
        org.springframework.core.io.ClassPathResource classPathResource = new org.springframework.core.io.ClassPathResource("sqlmap/MapperInterface.xml");
        definition.getPropertyValues().add("mapperLocations", classPathResource);
        Interceptor interceptor = MybatisBean.MapperConfiguration.SqlPrintInteceptor();
        Interceptor[] interceptors = { interceptor};
        definition.getPropertyValues().add("plugins", interceptors);
        applicationContext.registerBeanDefinition("sqlSessionFactory", definition);

    }
    @Bean
    public static DruidDataSource pgDruidDataSource() {
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName("org.postgresql.Driver");
        ds.setUrl(// Postgresql
                "jdbc:postgresql://localhost:5434/postgres?characterEncoding=utf8&useSSL=true&serverTimezone=Asia" +
                        "/Shanghai");
        ds.setMaxActive(5); // only max active is 1
        ds.setUsername("postgres");
        ds.setPassword("postgres");
        ds.setInitialSize(5);
        return ds;
    }
}
